package com.lzx.adx.report.support.strategy.v2.media;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.XIAO_MI)
public class XiaoMiCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);


        //2.从缓存加载配置
        Map<String, String> reqMap = new LinkedHashMap<>();
        reqMap.put("callback", URLEncoderDecoderTool.encodeURL(reportDTO.getCallback()));
        if (StringUtils.isNotBlank(reportDTO.getOaid())) {
            reqMap.put("oaid", reportDTO.getOaid());
        } else if (StringUtils.isNotBlank(reportDTO.getImei())) {
            reqMap.put("imei", reportDTO.getImei());
        }
        reqMap.put("conv_time", ts);
        reqMap.put("convType", eventType);
        String url = URLUtil.buildQuery(reqMap, StandardCharsets.UTF_8);
        String sign = SecureUtil.md5(url + jsonObject.getString(eventType));
        String resultUrl = accountDTO.getSspApiUrl() + "?" + url + "&sign=" + sign;
        log.info("账号id{},请求id{} 给小米上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号id{},请求id{} 给小米上报回传响应的结果为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);
        return ResponseEntity.ok(new Result());

    }
}
